//
//  BusinessChooseVC.m
//  NewPro
//
//  Created by 何荧红 on 2018/12/27.
//  Copyright © 2018 何荧红. All rights reserved.
//

#import "BusinessChooseVC.h"
#import "POSListVC.h"
#import "BusinessCooseCell.h"
#import "ToFriendViewController.h"

@interface BusinessChooseVC ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) ViewFoot *footview;
@property (nonatomic, strong) PushView *pushView;
@property (nonatomic, strong) PushView *success;
@property (nonatomic, strong) NSMutableDictionary *mutArr;
@property (nonatomic, strong) NSMutableArray *indexarr;
@property (nonatomic, strong) NSMutableArray *snArr;


@end

@implementation BusinessChooseVC

- (NSMutableDictionary *)mutArr{
    if (!_mutArr) {
        _mutArr = [[NSMutableDictionary alloc]init];
    }
    return _mutArr;
}
- (PushView *)pushView{
    if (!_pushView) {
        _pushView = [[PushView alloc]initWithChooseAlert];
    }
    return _pushView;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    self.navigationController.navigationBar.hidden = YES;
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:YES];
    self.navigationController.navigationBar.hidden = NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initCSS];
    if (_dataArr.count > 0) {
        [self loadData];
    }
}
- (void)loadData{
    [SAFRequestApi api_merchant_backAmount:_dataArr successBlock:^(id res) {
        if ([res[@"msg"] isEqualToString:@"success"]) {
            for (NSInteger i = 0; i < [res[@"data"][@"items"] count]; i++) {
                [self.mutArr setObject:@[res[@"data"][@"items"][[res[@"data"][@"items"] allKeys][i]],@{@"clik":@"0"}] forKey:[res[@"data"][@"items"] allKeys][i]];
            }
        }
        self.footview.allnumber = self.mutArr.count;
        [self findMinNumber];
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
    } failureBlock:^(id res) {
        [self.tableView.mj_header endRefreshing];
    }];
}
- (void)loadChoose{
    NSMutableArray *subArr = [[NSMutableArray alloc]init];
    if (self.snArr.count > 0) {
        for (NSDictionary *dic in self.snArr) {
            [subArr addObject:[[dic allKeys] firstObject]];
        }
    }
    NSMutableDictionary *prams = [[NSMutableDictionary alloc]init];
    [prams setObject:[UserDefaultsManager sharedInstance].user_id forKey:@"fromId"];
    [prams setObject:self.footview.numberfield.text forKey:@"backAmount"];
    [prams setObject:subArr forKey:@"snList"];
    if (self.pushView.choosename.length > 0) {
        [prams setObject:self.pushView.choosename forKey:@"toName"];
        if (self.pushView.choosephone.length > 0) {
            [prams setObject:self.pushView.choosephone forKey:@"toPhone"];
            [self loadChooseData:prams];
        }else{
            [self showMBPError:@"请输入用户手机号"];
        }
    }else{
        [self showMBPError:@"请输入用户名"];
    }
}
- (void)loadChooseData:(NSDictionary *)prams{
    [SAFRequestApi api_pos_flow:prams successBlock:^(id res) {
        if ([res[@"msg"] isEqualToString:@"success"]) {
            [self CleanSuccessAlert:1];
            [self.pushView removeFromSuperview];
        }else{
            [self CleanSuccessAlert:0];
        }
    } failureBlock:nil];
}
- (void)CleanSuccessAlert:(NSInteger )type{
    WS(weakself);
    UIViewController *subview = [self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count - 2];
    POSListVC *VC = nil;
    if ([subview isKindOfClass:[POSListVC class]]) {
        VC = (POSListVC *)subview;
    }
    self.success = [[PushView alloc]initWithChooseAlertType:type];
    [self.success setAlertTypeBlock:^{
        if (type == 0) {
            [weakself.success removeFromSuperview];
            weakself.pushView.hidden = NO;
        }
        if (type == 1) {
            if (VC) {
                [VC getPOSlist];
                [[AppDelegate sharedAppDelegate] popToViewController:VC];
            }
        }
    }];
    [self.view addSubview:self.success];
}

- (void)findMinNumber{
    if (self.mutArr.count > 0) {
        NSLog(@"%@",self.dataArr[0]);
        NSInteger min = [self.mutArr[self.dataArr[0]][0] integerValue];
        for (NSInteger i = 0; i < self.mutArr.count ; i++) {
            if (min > [self.mutArr[self.dataArr[i]][0] integerValue]) {
                min = [self.mutArr[self.dataArr[i]][0] integerValue];
            }
        }
        self.footview.minnumber = min;
    }else{
        self.footview.minnumber = 0;
    }
}
- (void)initCSS{
    WS(weakself)
    self.view.backgroundColor = [UIColor colorWithHexString:@"F4F4F4"];
    ViewHeader *header = [[ViewHeader alloc] initWithDefaultString:@"可划拨终端"];
    [self.view addSubview:header];
    self.footview = [[ViewFoot alloc]initWithBusinessChoose:_ControllerType];
    self.footview.tonextlab.backgroundColor = [UIColor colorWithHexString:@"999999"];
    self.footview.tonext.enabled = NO;
    [self.footview setMoneytosureBlock:^{
        [weakself tofriendView];
    }];
    [self.view addSubview:self.footview];
    [self.footview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.bottom.equalTo(self.view.mas_bottom);
        make.height.mas_equalTo(104);
    }];
    ViewHeader *secView = [[ViewHeader alloc]initWithBusinessChoose];
    [self.view addSubview:secView];
    [self indexlabWith:secView];
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 100) style:UITableViewStylePlain];
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        if (self.mutArr.count > 0) {
            [self.mutArr removeAllObjects];
        }
        [self loadData];
    }];
    [self.tableView registerClass:[BusinessCooseCell class] forCellReuseIdentifier:@"BusinessCooseCellID"];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(secView.mas_bottom).offset(1);
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.bottom.equalTo(self.footview.mas_top).offset(10);
    }];
}
- (void)tofriendView{
    WS(weakself);
    if (self.VCType == 1) {
        if (self.footview.numberfield.text.length > 0) {
            if ([NSString isNumber:self.footview.numberfield.text]) {
                NSInteger min = [self.footview.numberfield.text integerValue];
                if (min < 0) {
                    [self showMBPError:@"返现金额不能小于0"];
                }else if (min > self.footview.minnumber){
                    [self showMBPError:@"返现金额不能高于上限"];
                }else {
                    ToFriendViewController *VC = [[ToFriendViewController alloc]init];
                    VC.infoArr = _snArr;
                    VC.minmoney = self.footview.numberfield.text;
                    [[AppDelegate sharedAppDelegate] pushViewController:VC];
                }
            }else{
                [self showMBPError:@"请输入数字"];
            }
        }else{
            [self showMBPError:@"请输入返现金额"];
        }
    }
    if (self.VCType == 2) {
        if (self.footview.numberfield.text.length > 0) {
            if ([NSString isNumber:self.footview.numberfield.text]) {
                NSInteger min = [self.footview.numberfield.text integerValue];
                if (min < 0) {
                    [self showMBPError:@"返现金额不能小于0"];
                }else if (min > self.footview.minnumber){
                    [self showMBPError:@"返现金额不能高于上限"];
                }else{
                    if ([self.view.subviews containsObject:self.pushView]) {
                        self.pushView.hidden = NO;
                    }else{
                        [self.view addSubview:self.pushView];
                    }
                    [self.pushView setAlertsureBlock:^{
                        weakself.pushView.hidden = !weakself.pushView.hidden;
                        [weakself loadChoose];
                    }];
                }
            }else{
                [self showMBPError:@"请输入数字"];
            }
        }else{
            [self showMBPError:@"请输入返现金额"];
        }
    }
}
- (NSMutableArray *)indexlabWith:(UIView *)view{
    NSMutableArray *arr = [[NSMutableArray alloc]init];
    for (UILabel *sublab in view.subviews) {
        if ([sublab.text isEqualToString:@"序号"]) {
            [arr addObject:sublab];
        }
        if ([sublab.text isEqualToString:@"终端编号（SN）"]) {
            [arr addObject:sublab];
        }
        if ([sublab.text isEqualToString:@"返现金额设置范围（元）"]) {
            [arr addObject:sublab];
        }
        if ([sublab.text isEqualToString:@"选择"]) {
            [arr addObject:sublab];
        }
    }
    self.indexarr = arr;
    return arr;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.mutArr.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 30;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01f;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 1;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *foot = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 270, 1)];
    foot.backgroundColor = [UIColor colorWithHexString:@"EFEFEF"];
    return foot;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BusinessCooseCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BusinessCooseCellID"];
    cell.title.text = [NSString stringWithFormat:@"%ld",indexPath.section + 1];
    if (self.mutArr.count > 0) {
    
        NSDictionary *dic = @{self.dataArr[indexPath.section]:self.mutArr[self.dataArr[indexPath.section]]};
        cell.infodic = dic;
        cell.indexarr = self.indexarr;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithDictionary:self.mutArr[self.dataArr[indexPath.section]][1] copyItems:YES];
    if ([dict[@"clik"] isEqualToString:@"0"]) {
        [dict setObject:@"1" forKey:@"clik"];
    }else{
        [dict setObject:@"0" forKey:@"clik"];
    }
    BusinessCooseCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.infodic = @{self.dataArr[indexPath.section]:@[self.mutArr[self.dataArr[indexPath.section]][0],dict]};
    [self.mutArr setObject:@[self.mutArr[self.dataArr[indexPath.section]][0],dict] forKey:self.dataArr[indexPath.section]];
    [self SelectWithNumber];
}
- (void)SelectWithNumber{
    NSInteger indexValue = 0;
    self.snArr = [[NSMutableArray alloc]init];
    for (NSInteger i = 0; i < self.mutArr.count; i++) {
        NSArray *arr = self.mutArr[self.dataArr[i]];
        NSDictionary *dic = arr[1];
        if ([dic[@"clik"] isEqualToString:@"1"]) {
            [_snArr addObject:@{self.dataArr[i]:arr}];
            indexValue += 1;
        }
    }
    if (_snArr.count > 0) {
        NSInteger minn = [_snArr[0][[[_snArr[0] allKeys] firstObject]][0] integerValue];
        for (NSDictionary *dict in _snArr) {
            if (minn > [dict[[[dict allKeys] firstObject]][0] integerValue]) {
                minn = [dict[[[dict allKeys] firstObject]][0] integerValue];
            }
        }
        self.footview.minnumber = minn;
    }
    self.footview.cliknumber = indexValue;
    if (indexValue >= self.minnumber) {
        self.footview.tonextlab.backgroundColor = [UIColor colorWithHexString:@"0CA6F0"];
        self.footview.tonext.enabled = YES;
    }else{
        self.footview.tonextlab.backgroundColor = [UIColor colorWithHexString:@"999999"];
        self.footview.tonext.enabled = NO;
    }
}

@end
